'''
lss 吉安麻将
'''
from datetime import datetime
from logging.handlers import RotatingFileHandler

from flask import Flask, request, jsonify
import logging
import recommond_sr as sr

import time
import json
from collections import defaultdict

# 全局统计数据

# from douzero.env.game import GameEnv
# from douzero.evaluation.simulation import load_card_play_models
i = 0
app = Flask(__name__)

# 配置日志记录，设置日志文件最大大小和备份数量
log_filename = f"log/app_{datetime.now().strftime('%Y%m%d')}_jian.log"
handler = RotatingFileHandler(log_filename, maxBytes=10*1024*1024, backupCount=5)  # 10MB 的日志文件大小上限，备份数量为 5
formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)

app.logger.addHandler(handler)
app.logger.setLevel(logging.INFO)


player_stats = [defaultdict(int) for _ in range(4)]
player_kinds = [defaultdict(int) for _ in range(4)]
# 初始化全局统计字典
cnt = 0
win_player_position_count = {0: 0, 1: 0, 2: 0, 3: 0, -1: 0}
win_point = [0,0,0,0]
win_win_point = [0,0,0,0]
win_type = {}


def convert_single_quotes_to_double_quotes(json_str):
    # 将单引号替换为双引号
    json_str = json_str.replace("'", "\"")
    return json_str


def update_stats(game_result):
    """
    更新玩家胡法统计数据。

    参数:
    game_result (list): 单局游戏结果，每个子列表包含对应玩家的胡法编号。
    """
    for player_id, hand_types in enumerate(game_result):
        for hand in hand_types:
            player_stats[player_id][hand] += 1

def update_kinds(game_result):
    """
    更新玩家番型统计数据。

    参数:
    game_result (list): 单局游戏结果，每个子列表包含对应番型的胡法编号。
    """
    for player_id, hand_kinds in enumerate(game_result):
        for hand in hand_kinds:
            player_kinds[player_id][hand] += 1


def print_stats():
    """
    打印当前累计的胡法统计数据。
    """
    for player_id, hand_stats in enumerate(player_stats):
        print(f"玩家 {player_id} 的胡法统计：")
        for hand_type, count in hand_stats.items():
            print(f"  胡法 {hand_type}: {count} 次",end=" ")
    for player_id, hand_kinds in enumerate(player_kinds):
        print(f"玩家 {player_id} 的番型统计：")
        for hand_type, count in hand_kinds.items():
            print(f"  番型 {hand_type}: {count} 次",end=" ")

@app.route("/get_action", methods=["POST"])
def play():
    data = request.get_json()  # 解析 JSON 数据
    try:
        time1 = time.time()
        # print("get_action......" + str(time1))
        # print(data)

        # app.logger.info('Received data: %s', data)
        act, card = sr.get_action(data)

        # print(act, card)
        # print(card)
        # app.logger.info('Return data: %s%s', act, card)
        return jsonify({
            'action_type': act,
            'action_card': card
        }

        )
    except Exception as e:
        # app.logger.info('Received data: %s', data)
        return jsonify({"error": str(e)}), 400


@app.route("/ting_card", methods=["POST"])
def ting():
    try:

        data = request.get_json()  # 解析 JSON 数据
        # app.logger.info('Received data: %s', data)
        return jsonify({
            'error_no': 0,
            'error_msg': 'no error'
        }

        )
    except Exception as e:
        return jsonify({"error": str(e)}), 400

@app.route("/round_end", methods=["POST"])
def get_result():
    try:
        data = request.get_json()  # 解析 JSON 数据
        app.logger.info('Received data: %s', data)
        # print(data)
        time2 = time.time()
        # if data['win_player_position'] == 1 or data['win_player_position'] == 2 or data['win_player_position'] == 3 or data['win_player_position'] == 0:
        #     i = i + 1
        # # print("end......" + str(time2))
        # # app.logger.info('Return data: %s', best_act)pyt
        # print("winning:" + str(i))
        win_player_position = data.get('win_player_position', None)
        # 统计 win_player_position 出现的次数
        global cnt
        cnt = cnt + 1
        win_player_position_count[win_player_position] += 1
        print(win_player_position_count)

        # app.logger.info('Received hu data: %s', data['hu_type'])
        total_point = data.get('total_score', None)
        for i in range(4):
            win_point[i] = win_point[i] + total_point[i]

        win_win_point[win_player_position] += total_point[win_player_position]

        update_stats(data['hu_type'])
        update_kinds(data['hu_right'])

        if cnt % 100 == 0:
            app.logger.info("==========================================")
            app.logger.info("场次：{}".format(cnt))
            app.logger.info("玩家胜场：{}".format(win_player_position_count))
            app.logger.info("玩家得分：{}".format(win_point))
            app.logger.info("玩家胜场得分：{}".format(win_win_point))
            print_stats()
        print(win_win_point)
        print(win_point)

        return jsonify({
            'error_no': 0,
            'error_msg': 'no error'
        }
        )

    except Exception as e:
        return jsonify({"error": str(e)}), 400

if __name__ == '__main__':
    # data = {'room_id': 980829, 'acting_player_position': 0, 'played_cards': [[7, 17, 52], [9, 55], [8], [55, 41]], 'player_hand_cards': [[5, 6, 8, 22, 23, 23, 40, 49, 51, 34], [3, 4, 5, 18, 18, 25, 34, 49, 50, 53], [1, 1, 2, 3, 17, 19, 21, 35, 38, 41, 50, 54, 38], [1, 3, 5, 21, 24, 35, 36, 37, 50, 19]], 'action_seq': [[0, 7, 7], [1, 7, 9], [3, 2, 9, 9], [3, 7, 55], [0, 7, 17], [1, 1, 18, 19], [1, 7, 55], [2, 7, 8], [3, 7, 41], [0, 1, 39, 40], [0, 7, 52]], 'last_action': [0, 7, 52], 'player_chi_cards': [[[41, 40, 39]], [[17, 18, 19]], [], []], 'player_peng_cards': [[], [], [], [[9, 9, 9]]], 'player_gang_cards': [[], [], [], []], 'player_bugang_cards': [[], [], [], []], 'player_angang_cards': [[], [], [], []], 'player_bu_cards': [[], [], [], []], 'action_cards': {'0': []}, 'remain_card_stack': [19, 23, 52, 36, 53, 39, 54, 34, 34, 4, 54, 20, 8, 53, 20, 8, 38, 33, 37, 52, 41, 17, 39, 39, 18, 22, 38, 37, 33, 36, 22, 36, 54, 22, 25, 6, 50, 3, 40, 41, 25, 7, 35, 35, 2, 53, 21, 24, 23, 52, 33, 55, 6, 2, 51, 49, 5, 51, 7, 24, 4, 24, 55, 2, 33, 1, 20, 20, 9, 37, 7, 4, 21, 25, 51, 17, 49, 40, 6], 'king_cards': [7, 8]}


    # data = json.dumps(data, ensure_ascii=False, indent=4)
    # data = json.loads(data)
    #
    # lp.get_action(data)

    app.run(host='0.0.0.0', port='9995', debug="True")

